<template>
  <el-dialog v-model="visible" width="70%" append-to-body class="order-detail">
  <div class="order-import-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>订单导入</span>
<!--          <el-button type="primary" @click="downloadTemplate">下载模板</el-button>-->
          <el-button type="primary" @click="downloadFile">下载模板</el-button>
          <div v-if="downloadStatus">{{ downloadStatus }}</div>
        </div>
      </template>

      <el-upload
          class="upload-demo"
          drag
          action=""
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
          accept=".xlsx, .xls"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>

      </el-upload>

      <div v-if="file" class="file-info">
        <el-tag type="info">{{ file.name }}</el-tag>
        <el-button type="danger" size="small" @click="removeFile" circle>
          <el-icon><close /></el-icon>
        </el-button>
      </div>

      <el-button
          type="primary"
          :loading="loading"
          :disabled="!file"
          @click="submitUpload"
          style="margin-top: 20px;"
      >
        开始导入
      </el-button>

      <!-- 导入结果展示 -->
      <div v-if="importResult" class="import-result">
        <el-divider />
        <h3>导入结果</h3>
        <el-alert :title="`共处理 ${importResult.total} 条记录`" type="info" show-icon />
        <el-alert
            v-if="importResult.success > 0"
            :title="`成功导入 ${importResult.success} 条`"
            type="success"
            show-icon
            style="margin-top: 10px;"
        />
        <el-alert
            v-if="importResult.failure > 0"
            :title="`导入失败 ${importResult.failure} 条`"
            type="error"
            show-icon
            style="margin-top: 10px;"
        />

        <div v-if="errorList.length > 0" class="error-list">
          <h4>错误详情：</h4>
          <el-table :data="errorList" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="row" label="行号" width="80" />
            <el-table-column prop="message" label="错误信息" />
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { UploadFilled, Close } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const file = ref(null)
const loading = ref(false)
const importResult = ref(null)
const errorList = ref([])
const downloadStatus = ref('');
import { getToken } from "@/utils/auth";

// 处理文件选择
const handleFileChange = (uploadFile) => {
  if (!uploadFile.raw) return

  const isExcel = /\.(xlsx|xls)$/i.test(uploadFile.raw.name)
  const isLt10M = uploadFile.raw.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return
  }

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return
  }

  file.value = uploadFile.raw
}

// 移除文件
const removeFile = () => {
  file.value = null
  importResult.value = null
  errorList.value = []
}


const fileUrl = ref('http://pro.goohuan.com:8085/profile/orderDownExcel.xlsx');

const downloadFile = () => {
  const link = document.createElement('a');
  link.href = fileUrl.value;
  link.download = '订单导入模板.xlsx'; // 可以指定下载后的文件名

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};


const downloadFile1 = async () => {
  try {
    const response = await axios.get('http://pro.goohuan.com:8085/profile/orderDownExcel.xlsx', {
      // responseType: 'blob', // 重要：指定返回数据的类型为二进制流
    });

    // 创建一个链接元素，以便下载文件
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '订单模板.xlsx'); // 指定下载后文件的名称
    document.body.appendChild(link);
    link.click(); // 触发下载
    document.body.removeChild(link); // 清理DOM

    downloadStatus.value = '文件下载成功！';
  } catch (error) {
    downloadStatus.value = '文件下载失败：' + error.message;
  }
}

const downloadTemplate = () => {
  fetch('@/assets/files/orderDownExcel.xlsx')
      .then(response => response.blob())
      .then(blob => {
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '订单模板.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)
      })


}

// http://pro.goohoan.com:8085/upload/orderDownExcel.xlsx

// const downloadTemplate = () => {
//   const link = document.createElement('a')
//   link.href = '@/assets/files/orderDownExcel.xlsx'
//   link.download = 'orderDownExcel.xlsx' // 设置下载的文件名
//   document.body.appendChild(link)
//   link.click()
//   document.body.removeChild(link)
// }
// 下载模板
/*
const downloadTemplate = async () => {
  try {
    const response = await axios.get('/api/orders/template', {
      responseType: 'blob'
    })

    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '订单导入模板.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('模板下载成功')
  } catch (error) {
    ElMessage.error('模板下载失败: ' + error.message)
  }
}
*/

// 提交导入
const submitUpload = async () => {
  if (!file.value) return

  loading.value = true
  importResult.value = null
  errorList.value = []

  const formData = new FormData()
  formData.append('file', file.value)

  try {
    const response = await axios.post('/dev-api/business/order/exportOrderExportToShip', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ` + getToken()
      }
    })

    importResult.value = response.data.data
    errorList.value = response.data.errors || []

    console.log("-----response---" + response)
    console.log("-----response.data---" + response.data)

    if (response.data.code === 200) {
      ElMessage.success(response.data || '导入成功')
    } else {
      ElMessage.warning(response.data || '导入完成，但有部分错误')
    }
  } catch (error) {
    ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const init = () => {
  file.value = null
  visible.value = true
  downloadStatus.value = '';
}

defineExpose({
  init
});
</script>

<style scoped>
.order-import-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-demo {
  width: 100%;
}

.file-info {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.import-result {
  margin-top: 20px;
}

.error-list {
  margin-top: 20px;
}
</style>